package ltd.goods.cloud.newbee.controller;

import ltd.common.newbee.cloud.entity.NewBeeGoodsInfo;
import ltd.common.newbee.cloud.param.ComplexObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Auther: tangyushan
 * @Date: 2024/5/24 - 05 - 24 - 17:33
 * @Description: ltd.newbee.cloud.api
 * @version: 1.0
 */
@RestController
public class NewBeeCloudGoodsAPI {

    @Value("${server.port}")
    private String applicationServerPort;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/goods/{goodsId}")
    public String goodsDetail(@PathVariable("goodsId") int goodsId) {
        //根据id查询商品并返回调用端
        if (goodsId < 1 || goodsId > 100000) {
            return "查询商品为空，当前服务的端口号为" + applicationServerPort;
        }
        String goodsName = "商品" + goodsId;
        //返回信息给调用端
        return goodsName + ",当前服务的端口号为：" + applicationServerPort;
    }



    @PostMapping("/goods/updNewBeeGoodsInfo")
    public NewBeeGoodsInfo updNewBeeGoodsInfo(@RequestBody NewBeeGoodsInfo newBeeGoodsInfo){
        if(newBeeGoodsInfo.getGoodsId() > 0) {
            int stock = newBeeGoodsInfo.getStock();
            stock -= 1;
            //库存减1
            newBeeGoodsInfo.setStock(stock);
        }
        return newBeeGoodsInfo;
    }

    @PostMapping("/goods/testComplexObject")
    public ComplexObject testComplexObject(@RequestBody ComplexObject complexObject) {
        int requestNum = complexObject.getRequestNum();
        requestNum -= 1;
        complexObject.setRequestNum(requestNum);
        //由于字段过多，因此这里用debug方式来查看接收的复杂对象参数
        return complexObject;
    }

    @PutMapping("/goods/{goodsId}")
    public Boolean deStock(@PathVariable("goodsId") int goodsId) {
        //减库存操作
        int result = jdbcTemplate.update("update tb_goods set goods_stock = goods_stock - 1 where goods_id = " + goodsId);
//        //模拟网络波动问题
//        try {
//            Thread.sleep(10*1000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        if (result > 0) {
            return true;
        }
        return false;
    }

}
